import * as _ from 'lodash';
import { environment } from './../../environments/environment';
import * as moment from 'moment';

export class Util {
  public static $ = window["$"];

  // URL
  public static noCacheUrl(url: string): string {
    const timestamp = "t=" + ((new Date()).getTime());
    const prefix = ((url.indexOf("?") !== -1) ? "&" : "?");

    return (url + prefix + timestamp);
  }
  /**
   * 日期时间范围插件daterangepicker初始化
   * @param {string} selector 要被初始化DOM元素css选择器
   * @param {string} config 配置对象
   * @param {boolean} mergeDefaultConfig 是否以默认配置为基础，进行默认配置和用户配置对象进行合并
   */
  public static daterangepickerPluginInit(selector: string = "", config: Object = {}, mergeDefaultConfig: boolean = true) {
    const defaultConfig = {
      autoUpdateInput: false,
      "locale": {
        applyLabel: '确定',
        cancelLabel: '清空',
        format: "YYYY-MM-DD",
        separator: " - ",
        daysOfWeek: [
          "日",
          "一",
          "二",
          "三",
          "四",
          "五",
          "六"
        ],
        monthNames: [
          "一月",
          "二月",
          "三月",
          "四月",
          "五月",
          "六月",
          "七月",
          "八月",
          "九月",
          "十月",
          "十一月",
          "十二月"
        ]
      },
    };
    if (mergeDefaultConfig) {
      config = Util.$.extend(true, {}, defaultConfig, config);
    }
    Util.$(selector).daterangepicker(config).on('apply.daterangepicker', function (ev, picker) {
      Util.$(this).val(picker.startDate.format('YYYY-MM-DD') + ' 至 ' + picker.endDate.format('YYYY-MM-DD'));
    }).on('cancel.daterangepicker', function () {
      Util.$(this).val('');
    });
  }

  /**
   * 日期插件datepicker初始化
   * @param {string} selector 要被初始化DOM元素css选择器
   * @param config 配置对象
   * @param {boolean} mergeDefaultConfig 是否以默认配置为基础，进行默认配置和用户配置对象进行合并
   */
  public static datepickerPluginInit(selector: string = "", config: Object = {}, mergeDefaultConfig: boolean = true) {
    const defaultConfig = {
      language: "zh-CN",
      format: "yyyy-mm-dd"
    };
    if (mergeDefaultConfig) {
      config = Util.$.extend(true, {}, defaultConfig, config);
    }
    Util.$(selector).datepicker(config);
  }

  /**
   * 附件下载
   * @param attachNoList 附件内码
   */
  public static attachDownload(attachNoList) {
    // 下载链接
    let downloadURL = "";

    // 构建下载链接
    if (attachNoList.length == 1) { // 单个文件下载
      downloadURL = "/pms/v1/common/fundFile/file/" + attachNoList[0] + "?token=" + sessionStorage.getItem('token');
    } else { // 多个文件下载
      downloadURL = "/pms/v1/common/fundFile/files?token=" + sessionStorage.getItem('token') + '&attachNos=' + attachNoList.join(',');
    }

    // 下载
    let iframe = window['$']("<iframe id='downloadiframe'>");
    iframe.attr('style', 'display:none');
    iframe.attr('src', environment.server + downloadURL);
    window['$']('body').append(iframe);
    setTimeout("$('#downloadiframe').remove()", 60000);

  }
  // *必填日期前后校验,frontDate为前日期,afterDate为后日期
  public static dateOrder(frontDate: any, afterDate: any) {
    if (frontDate !== "" && frontDate !== null && afterDate !== "" && afterDate !== null) {
      if (frontDate == afterDate) {
        return true;
      } else {
        if (moment(frontDate).isBefore(afterDate)) {
          return true;
        } else {
          return false;
        }
      }
    } else {
      return true;
    }
  }
  // *养老金部产品续约日期自动增加,date为基础日期，term为年限
  public static dateIncrease(sDate: any, term: any) {
    let rspDate = moment(sDate).add('months', term * 12).format('YYYY/MM/DD');
    return moment(rspDate).format('YYYY-MM-DD');
  }
  /**
   * 对象是否相等校验
   * @param list 数组一
   * @param listClone 数组二
   */
  public static objectCheck(list, listClone) {
    _.forIn(list, (value, key) => {
      if (value == null) {
        list[key] = '';
      }
    })
    _.forIn(listClone, (value, key) => {
      if (value == null) {
        listClone[key] = '';
      }
    })
    if (_.eq(JSON.stringify(list), JSON.stringify(listClone))) {
      return true;
    } else {
      return false;
    }
  }
  /**
   * 计算字符串字符长度,中文英文混合判断
   * @param item 需要计算的字符串
   */
  //计算字符串字符长度
  public static mathStringLength(item) {
    var realLength = 0;
    if (item) {
      for (var i = 0; i < item.length; i++) {
        var charCode = item.charCodeAt(i);
        if (charCode >= 0 && charCode <= 128)
          realLength += 1;
        else
          realLength += 2;
      }
      return realLength;
    }
  }

  // select插件，支持多选，在html配置multiple属性，传入字典值、id即可。在ngOninit初始化函数。
  public static loadSelect(field, id, width?) {
    var html = '';
    for (var i = 0; i < field.length; i++) {
      // console.log(field[i].sItemValue);
      html += "<option value='" + field[i].sItemKey + "'>" + field[i].sItemValue + "</option>";
    }
    window['$']("#" + id).html(html);

    window['$']('#' + id).selectpicker({
      size: "8",
      actionsBox: "true",
      title: "请选择",
      selectAllText: "全选",
      deselectAllText: "取消全选",
      width: width ? width : 180,
      liveSearch: true, //搜索功能
      dropupAuto: false
    });

  }
  /**
   * 
   * 切换tab，自动active第一个tab的函数，传入两个数组。
   * @static
   * @param {any} tabInLiArray 
   * @param {any} tabInaArray 
   * @memberof Util
   * 
   * 
   * eg:
   *   <li id="zhxx">   <------tabInLiArray
         <a href="#tab_1" data-toggle="tab" >组合信息</a>    <------tabInaArray
       </li>
   */
  public static activeFirstTab(tabInLiArray, tabInaArray) {
    _.forEach(tabInLiArray, item => {
      window['$']('#' + item).removeClass('active');
    })
    _.forEach(tabInaArray, item => {
      window['$']('#' + item).removeClass('active');
    })
    window['$']('#' + tabInLiArray[0]).addClass('active');
    window['$']('#' + tabInaArray[0]).addClass('active');
  }

  /**
   * 处理字典值，返回一个数组，给多选下拉框
   * 
   * @static
   * @param {any} dictionaryValue 
   * @returns 
   * @memberof Util
   */
  public static loadPrimeSelect(dictionaryValue) {
    let returnArray = [];
    _.forEach(dictionaryValue, item => {
      // console.log(item);
      returnArray.push({
        label: item.sItemValue,
        value: item.sItemKey
      })
    })
    return returnArray;
  }

  /**
   * 用于去除postbody前后的空格，传入对象循环后返回。
   * 
   * @param {Object} postBodyObject 
   * @returns 
   * @memberof Util
   */
  public static trimPostItem(postBodyObject) {
    _.forEach(postBodyObject, (postItem, i) => {
      postBodyObject[i] = _.trim(postBodyObject[i])
    })
    return postBodyObject;
  }
  /**
   * 用于刷新列表时清空搜索条件
   * 
   * @static
   * @param {Object} Object 
   * @param {Array} exclude  不清空项目，一般为pageSize、pageIndex
   * @memberof Util
   */
  public static clearSearchConditions(body, exclude: any[]) {

    _.forIn(body, (value, key) => {
      if (!_.includes(exclude, key)) {
        body[key] = ''
      }
    })
    return body;
  }
  /**
   * 用于获取权限数据
   * @static
   * @param {any} firstLevelMenu 一级菜单
   * @param {any} secondLevelMenu 二级菜单
   * @param {any} [thridLevelMenu] 三级菜单
   * @returns 
   * @memberof Util
   */
  public static getAuthority(firstLevelMenu, secondLevelMenu, thridLevelMenu?) {
    let SessionMenuData = sessionStorage.getItem('menu');
    let menuData = JSON.parse(SessionMenuData)
    let list1: any = _.filter(menuData, (item: any) => { return item.sName == firstLevelMenu });
    let list2: any = _.filter(list1[0].children, (item: any) => { return item.sName == secondLevelMenu });
    if (thridLevelMenu != undefined) {
      let list3: any = _.filter(list2[0].children, (item: any) => { return item.sName == thridLevelMenu });
      // console.log(thridLevelMenu)
      // console.log(JSON.stringify(list1))
      // console.log(list2)
      // console.log(list3)
      return list3[0].resourceSet
    } else {
      return list2[0].resourceSet
    }
  }
  // 多选下拉框字段转换,id为唯一class标识
  public static transferValue(id) {
    let transferValue = [];
    let dataList = window['$'](id).val();
    _.forEach(dataList, item => {
      let index1 = item.indexOf("'");
      let index2 = item.lastIndexOf("'");
      let value = item.substring(index1 + 1, index2);
      transferValue.push(value);
    })
    let stransferValue = transferValue.join(",");
    return stransferValue;
  }
}

